package com.sumainfor.pc.market.service.tenant.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Lists;
import com.google.gson.reflect.TypeToken;
import com.sumainfor.common.Constants;
import com.sumainfor.common.ConstantsHousing;
import com.sumainfor.common.EQBtsignConstants;
import com.sumainfor.common.entity.UploadResult;
import com.sumainfor.common.entity.WxUserEntity;
import com.sumainfor.common.exception.TCException;
import com.sumainfor.common.util.*;
import com.sumainfor.common.utlis.CompuUtils;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.market.dao.TcmktTenantBlaMapper;
import com.sumainfor.pc.market.dao.tenant.SignedProviderMapper;
import com.sumainfor.pc.market.feign.BaseFeignEpc;
import com.sumainfor.pc.market.feign.TenantFeign;
import com.sumainfor.pc.market.feign.Zfeign.ZpcGmioFeign;
import com.sumainfor.pc.market.service.tenant.SignedProviderService;
import lombok.extern.log4j.Log4j2;
import okhttp3.*;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author Eddy·Chen
 * @Email 835033913@qq.com
 * @Create 2019-02-25 17:59
 */
@Service
@Log4j2
@Transactional(rollbackFor = Exception.class)
public class SignedProviderServiceImpl implements SignedProviderService {

    @Autowired
    private SignedProviderMapper signedProviderMapper;

    /**
     * 通知的回调接口
     */
    private static final String NOTICE_URL = "http://47.96.150.97:7000/wechat/tenant/signed/noticeStateResult";



    public static final String REDURECT_URL = "http://www.4006269069.net/#/checkPay?payType=%d&KeyId=%s";

    @Autowired
    private TenantFeign tenantFeign;

    @Autowired
    private HttpUtil httpUtil;

    @Autowired
    private RemoteFileUpload remoteFileUpload;

    @Autowired
    private ZpcGmioFeign gmioFeign;

    @Autowired
    private TcmktTenantBlaMapper tcmktTenantBlaMapper;

    @Autowired
    private BaseFeignEpc epcFeign;

    /**
     * 创建合同信息 新签合同
     *
     * @param params
     * @return
     */
    @Override
    public JsonResult<CustomMap> createPact(Map<String, Object> params) {
        String[] field = {"TenId", "id"};

        if (!FieldCheckUtil.isMapFieldNotNull(params, field)) {
            return JsonResult.errorForEmpty();
        }
        params.put("name", "上海唐巢公共租赁住房运营有限公司");
        params.put("templateId","bb2dbe7fab094d79be43b8ec61521700");
        params.put("callBackType", 1);

        log.info("templateId11111111111111111111111111111111111");
        log.info("templateId"+params.get("templateId"));

        return createBase(params);
    }

    /**
     * 续签合同
     *
     * @param params
     * @return
     */
    @Override
    public JsonResult<CustomMap> createRenewPact(Map<String, Object> params) {
        String[] field = {"TenId", "id"};

        if (!FieldCheckUtil.isMapFieldNotNull(params, field)) {
            return JsonResult.errorForEmpty();
        }
        params.put("name", "上海唐巢公共租赁住房运营有限公司");
        params.put("templateId","bb2dbe7fab094d79be43b8ec61521700");
        params.put("callBackType", 3);
        return createBase(params);
    }

    /**
     * 基本的合同创建流程
     *
     * @param params
     * @return
     */
    private JsonResult<CustomMap> createBase(Map<String, Object> params) {
        //合同编号
        String pactId = MapUtils.getString(params, "id");


        String tenId = MapUtils.getString(params, "TenId");
        //查询租客信息
        JsonResult<WxUserEntity> result = tenantFeign.getWxInfoByTenId(tenId);
        if (!result.isSuccess()) {
            log.info("Error ==> {}", result.getErrorMessage());
            return JsonResult.error("没有查询到租客的信息");
        }
        WxUserEntity userEntity = JSONObject.parseObject(JSONObject.toJSONString(result.getResult()), new TypeReference<WxUserEntity>() {
        });
        //判断是否需要创建用户
        if (StringUtils.isBlank(userEntity.getPactAccountId())) {
            //创建
            JsonResult<Map<String, Object>> post = httpUtil.doPost(EQBtsignConstants.URL_PREFIX + "/account/create/person", CustomMap.create()
                    .put("thirdId", userEntity.getTenId())
                    .put("name", userEntity.getRealName())
                    .put("idNo", userEntity.getCardId())
                    .put("idType", 19)
                    .put("mobile", userEntity.getTenPhone())
            );
            if (!post.isSuccess()) {
                log.error("创建用户失败 {}", post);
                return JsonResult.error("创建用户失败");
            }
            userEntity.setPactAccountId((String) post.getResult().get("accountId"));
            //更新到租客端 保存这个 Account Id
            JsonResult jsonResult = tenantFeign.updateWxInfoByTenId(CustomMap.create("TenId", userEntity.getTenId())
                    .put("PactAccountId", userEntity.getPactAccountId()));
            if (!jsonResult.isSuccess()) {
                //删除这个用户
                httpUtil.doPost(EQBtsignConstants.URL_PREFIX + "/account/delete", CustomMap.create("accountId", userEntity.getPactAccountId()));
                return JsonResult.error("更新到数据失败");
            }
        }
        log.info("simpleFormFields里面的参数111111111111111111111");
        log.info("params"+params);
        //创建合同
        JsonResult<Map<String, Object>> pactResponse = httpUtil.doPost(EQBtsignConstants.URL_PREFIX + "/doc/createbytemplate", CustomMap.create("simpleFormFields", params)
                .put("templateId", MapUtils.getString(params, "templateId"))
                .put("name", MapUtils.getString(params, "name"))
        );
        if (pactResponse.isSuccess() == false) {
            log.error("创建合同失败 {}", pactResponse);
            return JsonResult.error("创建合同失败");
        }
        Map<String, Object> pactMain = pactResponse.getResult();
        //创建合同签署流程
        JsonResult<Map<String, Object>> flowldRes = httpUtil.doPost(EQBtsignConstants.URL_PREFIX + "/sign/contract/addProcess", CustomMap.create("businessScene", "唐巢租赁新签合同")
                .put("signPlatform", "1")
                .put("noticeType", "")
                .put("initiatorAccountId", "e24627288b3e4f75aaa39f7ab9b26d10")
                .put("docId", MapUtils.getString(pactMain, "docId"))
                //签署跳转地址
                .put("noticeUrl", NOTICE_URL)
                .put("redirectUrl", String.format(REDURECT_URL, MapUtils.getInteger(params, "callBackType", 1), pactId))
                .put("addSignTime", true)
        );
        if (flowldRes.isSuccess() == false) {
            log.error("合同创建异常 {}", flowldRes);
            throw new TCException("合同创建异常");
        }
        //流程ID
        String flowId = MapUtils.getString(flowldRes.getResult(), "flowId");
        //创建自动签署

        JsonResult<Map<String, Object>> autoPactRes = httpUtil.doPost(EQBtsignConstants.URL_PREFIX + "/sign/contract/platformSignTask", CustomMap.create("flowId", flowId)
                .put("posList", Lists.newArrayList(CustomMap.create()
                        .put("signType", "1")
                        .put("key", "chuzugaizhang")
                ))
                .put("sealId","364ff7dc-daef-4d11-9685-70458ecab6ec")
        );
        if (autoPactRes.isSuccess() == false) {
            //自动签署失败 撤销签署流程
            log.error("合同创建异常 Fl {}", autoPactRes);
            httpUtil.doPost(EQBtsignConstants.URL_PREFIX + "/sign/revoke", CustomMap.create("flowId", flowId));
            throw new TCException("合同创建异常 Fl");
        }
        flowId = MapUtils.getString(autoPactRes.getResult(), "flowId");
        //发起个人手动签署
        JsonResult<Map<String, Object>> signUserPact = httpUtil.doPost(EQBtsignConstants.URL_PREFIX + "/sign/contract/handPersonSignTask", CustomMap.create("flowId", flowId)
                .put("accountId", userEntity.getPactAccountId())
                .put("sealType", "0")
                .put("thirdOrderNo", pactId)
                .put("posList", Lists.newArrayList(CustomMap.create("signType", 1)
                        .put("key", "chenzugaizhang")
                ))
        );
        if (signUserPact.isSuccess() == false) {
            //自动签署失败 撤销签署流程
            log.error("合同创建异常 F2 {}", signUserPact);
            httpUtil.doPost(EQBtsignConstants.URL_PREFIX + "/sign/revoke", CustomMap.create("flowId", flowId));
            throw new TCException("合同创建异常 F2");
        }
        //成功了 永久的地址
        String signUrl = MapUtils.getString(signUserPact.getResult(), "signUrl");

        CustomMap data = CustomMap.create("FlowId", flowId)
                .put("FlowStatus", 1)
                .put("SignUrl", signUrl);

        return JsonResult.success(data);
    }

    /**
     * 撤销签署
     *
     * @param flowId
     * @return
     */
    @Override
    public JsonResult removePactFlow(String flowId) {
        if (StringUtils.isBlank(flowId)) {
            return JsonResult.errorForEmpty();
        }
        JsonResult<Map<String, Object>> post = httpUtil.doPost(EQBtsignConstants.URL_PREFIX + "/sign/revoke", CustomMap.create("flowId", flowId));
        return post;
    }

    /**
     * 查看合同签署进度
     *
     * @param flowId
     * @return
     */
    @Override
    public JsonResult getPactFlowInfo(String flowId) {
        JsonResult<Map<String, Object>> result = httpUtil.doPost(EQBtsignConstants.URL_PREFIX + "/sign/contract/detail", CustomMap.create("flowId", flowId));
        if (result.isSuccess() == false) {
            return JsonResult.actionFailure();
        }
        return result;
    }

    /**
     * 通知消息回调接口 异步
     *
     * @param params
     * @return
     */
    @Override
    public JsonResult noticeStateResult(Map<String, Object> params) {
        String action = MapUtils.getString(params, "action");
        if (action.equals("SIGN_FLOW_UPDATE")) {
            //签署流程结束通知
            String flowId = MapUtils.getString(params, "flowId");
            int signResult = MapUtils.getIntValue(params, "signResult");
            //查询合同主表通过FlowId
            Map<String, Object> data = signedProviderMapper.getPactMainByFlowId(flowId);
            if (MapUtils.isEmpty(data)) {
                throw new TCException(500, "没有查询到合同信息");
            }
            if (!MapUtils.getInteger(data, "FlowStatus").equals(1)) {
                return JsonResult.error("合同已操作,不可重复操作");
            }
            CustomMap updateParams = CustomMap.create("FlowId", flowId)
                    .put("FlowStatus", signResult)
                    .put("IfFlowPay", 1)
                    .put("FlowTime", DateUtils.stringToDate(MapUtils.getString(params, "signTime"), "yyyy-MM-dd HH:mm:ss"))
                    .put("StatusDescription", MapUtils.getString(params, "resultDescription"));
            ParamsCommon.commonUpdateParms(updateParams);
            int state = signedProviderMapper.updatePactMain(updateParams);
            if (state <= 0) {
                throw new TCException(500, "更新合同失败");
            }
            //归档
            this.setPactStateForDone(flowId);
            //如果没有下载过合同那么就先去下载合同
            if (StringUtils.isBlank(MapUtils.getString(data, "PactFile")) && signResult == 2) {
                //下载合同
                this.downloadPactFile(flowId);
            }
            Timestamp startTime = (Timestamp) data.get("StartTime");
            Timestamp endTime = (Timestamp) data.get("EndTime");

            DateTime begin = new DateTime(startTime.getTime());
            DateTime end = new DateTime(endTime.getTime());
            //获取月份
            String parrent = "yyyy-MM-dd";
            int months = Math.abs(DateUtils.getMonthDiff(begin.toString(parrent), end.toString(parrent), parrent));

            CustomMap addPactData = CustomMap.create()
                    .put("payFu", months) //签约时长（时间相减）
                    // .put("monthMoney", data.get("PaActMonthPrice"))
                    .put("monthMoney", data.get("BillMonthPrice"))//账单金额
                    .put("Firstmonth", data.get("Firstmonth"))//合同首月金额
                    .put("SenSend",data.get("SenSend"))//签约满送时长
                    .put("actualDeposit",data.get("actualDeposit"))//押金
                    .put("BroadBand",data.get("BroadBand"))//宽带费用
                    .put("IsWater",data.get("IsWater"))//水费是否是定额定价（0 否 1 是）
                    .put("IsGas",data.get("IsGas"))//燃气费是否定额定价（0 否 1 是）
                    .put("WaterPricing",data.get("WaterPricing"))//水费定价
                    .put("GasPricing",data.get("GasPricing"))//燃气费定价
                    .put("ChaId",data.get("ChaId"))//水电燃收费标准编号
                    .put("bottomADate", begin.toString("yyyy-MM-dd"))//合同开始周期
                    .put("endADate", end.toString("yyyy-MM-dd"))//合同开始周期
                    .put("TenId", data.get("TenId")) //租客编号
                    .put("HouId", data.get("HouId")) //房源编号
                    .put("HouInfoId", data.get("HouInfoId")) //房源详表编号
                    .put("CorId", data.get("CorId")) //房源所属的公司编号
                    .put("WaDeposit", data.get("WaDeposit")) //水电押金
                    .put("payYa", data.get("Deposit")) //押几个月
                    .put("Pmethod", data.get("Pmethod"))//支付方式
                    .put("ProOperaType",data.get("ProOperaType"))//租赁类型（1.合租 2.整租）
                    .put("PaId", data.get("PaId")); //合同编号

            log.info("gmioFeign.addTenantBillForPact 传入参数====>{}", addPactData);
            JsonResult result = gmioFeign.addTenantBillForPact(addPactData);
            log.info("gmioFeign.addTenantBillForPact 返回结果====>{}", result);
            if (result.isSuccess() == false) {
                log.error("gmioFeign.addTenantBillForPact ERROR:" + result.getErrorMessage());
                throw new TCException("生成账单失败");
            }

        } else {
            throw new TCException("Action 不匹配:" + SystemUtils.getLineNumber());
        }

        return JsonResult.success();
    }

    /**
     * 下载PDF文件到七牛云
     *
     * @param flowId
     */
    private void downloadPactFile(String flowId) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), JSONObject.toJSONString(CustomMap.create("flowId", flowId)));
        httpUtil.doPost(EQBtsignConstants.URL_PREFIX + "/sign/download", requestBody).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                log.error("获取合同文件出错");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String body = response.body().string();
                    Map<String, Object> data = JSONObject.parseObject(body, new TypeToken<Map<String, Object>>() {
                    }.getType());
                    if (MapUtils.getInteger(data, "errCode") != 0) {
                        throw new TCException("请求下载文件失败");
                    }
                    Map<String, Object> map = ((List<Map<String, Object>>) MapUtils.getObject(data, "data")).get(0);
                    String url = MapUtils.getString(map, "docUrl");
                    //进行下载操作
                    httpUtil.doGet(url).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            log.error("下载文件出错");
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            File tempFile = FileUtils.getTempDirectory();
                            InputStream inputStream = response.body().byteStream();
                            byte[] bytes = new byte[1024];
                            int len;
                            String uuid = UUIDUtils.generateShortUuid();
                            File tempPdf = new File(tempFile, String.format("%s.pdf", uuid));
                            FileOutputStream fos = new FileOutputStream(tempPdf);
                            while ((len = inputStream.read(bytes)) != -1) {
                                fos.write(bytes, 0, len);
                            }
                            fos.flush();
                            IOUtils.closeQuietly(fos);
                            IOUtils.closeQuietly(inputStream);
                            response.close();
                            JsonResult<UploadResult> upload = remoteFileUpload.upload(tempPdf);
                            if (upload.isSuccess()) {
                                UploadResult result = upload.getResult();
                                String url = result.getAbsoluteUrl();
                                log.info("上传七牛云成功:{}", url);
                                //更新文件地址
                                int row = signedProviderMapper.updatePactMain(CustomMap.create("FlowId", flowId)
                                        .put("PactFile", url)
                                );
                                if (row <= 0) {
                                    log.error("更新合同文件PDF失败");
                                }
                            } else {
                                log.error("上传文件出错:{}", upload.getErrorMessage());
                            }
                        }
                    });

                }
                response.close();
            }
        });
    }


    /**
     * 设置合同归档操作
     *
     * @param flowId
     */
    private void setPactStateForDone(String flowId) {
        JsonResult<Map<String, Object>> result = httpUtil.doPost(EQBtsignConstants.URL_PREFIX + "/sign/contract/archiveProcess", CustomMap.create("flowId", flowId));
        log.info("归档返回参数： =====> {}", result);
        if (result.isSuccess() == false) {
            throw new TCException("归档失败");
        }
    }

    /**
     * 获取等待签约数据列表
     *
     * @return
     */
    public List<Map<String, Object>> getWaitSignList(Map<String, Object> params) {
        List<Map<String, Object>> getWaitSignList = signedProviderMapper.selectWaitSignList(params).stream().map(item -> {
//            item.put("ST", item.remove("ProLoculus") + "室" + item.remove("ProHall") + "厅");
            StringBuilder house = new StringBuilder();
            if (!StringUtils.isBlank(MapUtils.getString(item, "ProLoculus"))) {
                if (!StringUtils.isBlank(MapUtils.getString(item, "ProHall"))) {
                    if (!StringUtils.isBlank(MapUtils.getString(item, "ProGuard"))) {
                        house.append(item.get("ProLoculus").toString());
                        house.append("室");
                        house.append(item.get("ProHall").toString());
                        house.append("厅");
                        house.append(item.get("ProGuard").toString());
                        house.append("卫");
                    } else {
                        house.append(item.get("ProLoculus").toString());
                        house.append("室");
                        house.append(item.get("ProHall").toString());
                        house.append("厅");
                    }
                } else {
                    house.append(item.get("ProLoculus").toString());
                    house.append("室");
                }
                item.put("house", house);
            } else {
                item.put("house", null);
            }

            //图片处理
            if (!StringUtils.isNotBlank(MapUtils.getString(item, "ShowImg"))) {
                item.put("ShowImg", ConstantsHousing.DefaultHousingImg);
            }


            return item;
        }).collect(Collectors.toList());
//        return JsonResult.success(signedProviderMapper.selectWaitSignList(tenId).stream().map(item -> {
//            item.put("Floor", item.get("Floor") + "/" + item.remove("Floors"));
//            item.put("Area", item.get("Area") + "㎡");
//            item.put("ST", item.remove("ProLoculus") + "室" + item.remove("ProHall") + "厅");
//            return item;
//        }).collect(Collectors.toList()));
        return getWaitSignList;
    }

    /**
     * 功能描述:
     * 根据合同编号获取合同状态
     * FlowStatus 电子合同签署状态  \n1.签署中\n2:签署完成\n3:失败\n4:拒签
     * IfFlowPay  电子合同是否支付     0无状态   1已完成未支付    2已完成已支付（该状态只有电子合同状态为2才有用）
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/3/20 10:32
     */
    public Map<String, Object> getPactStatus(Map<String, Object> params) {
        Map<String, Object> getPactStatus = signedProviderMapper.getPactStatus(params);
        return getPactStatus;
    }

    /**
     * 根据合同编号查询签约流程第一个流程的数据
     *
     * @return
     */
    public Map<String, Object> getPactSignFlowOne(Map<String, Object> params) {
        Map<String, Object> getPactSignOneData = signedProviderMapper.getPactSignOneData(params);
        log.info("getPactSignOneData---" + getPactSignOneData);
        if (FieldCheckUtil.isMapFieldNotNull(getPactSignOneData, new String[]{"ActivityInfo"})) {
            String[] ActivityInfo = getPactSignOneData.get("ActivityInfo").toString().split(",");
            getPactSignOneData.put("ActivityInfo", ActivityInfo);
        } else {
            getPactSignOneData.put("ActivityInfo", new ArrayList<Map<String, Object>>());
        }
        return getPactSignOneData;
    }

    /**
     * 查询签约流程第二步数据;
     *
     * @param pactId
     * @return
     */
    @Override
    public JsonResult getPactSignFlowTwo(String pactId) {
        return JsonResult.success(signedProviderMapper.getPactSignTwoData(pactId));
    }

    /**
     * 查询签约流程第三步和第四步数据;
     *
     * @param pactId
     * @return
     */
    @Override
    public JsonResult getPactSignThreeAndFour(String pactId) {
        Map<String, Object> chaInfo = signedProviderMapper.getPactSignThreeAndFour(pactId);
        if (MapUtils.isEmpty(chaInfo)) {
            return JsonResult.error("合同不存在");
        }
        //根据收费标准编号查询收费标准价格
        JsonResult<JSONObject> chaJson = gmioFeign.getChargesData(MapUtils.getString(chaInfo, "ChaId"));
        if (!chaJson.isSuccess()) {
            return chaJson;
        }
        JSONObject result = chaJson.getResult();
        if (MapUtils.getInteger(chaInfo, "IsWater").equals(0)) {
            //判断水费是否定额还是定价
            chaInfo.put("WaterPrice", result.getString("WaterPricing") + " 元/吨");
        } else {
            chaInfo.put("WaterPrice", result.getString("WaterPricings") + " 元/月/人");
        }

        if (MapUtils.getInteger(chaInfo, "IsGas").equals(0)) {
            //判断燃气费是否定额还是定价
            chaInfo.put("GasPrice", result.getString("GasPricing") + " 元/m³");
        } else {
            chaInfo.put("GasPrice", result.getString("GasPricings") + " 元/月/人");
        }

        chaInfo.put("ElPrice", result.getString("EleFee") + " 元/度");

        //获取房间号码
        String number = MapUtils.getString(chaInfo, "HouInfoId");
        number = number.substring(number.length() - 1);
        List<Map<String, Object>> array = JSONObject.parseObject(MapUtils.getString(chaInfo, "Rests"), new TypeReference<List<Map<String, Object>>>() {
        });
        if (array!=null) {
            for (int i = 0; i < array.size(); i++) {
                if (MapUtils.getString(array.get(i), "houName").equals(number)) {
                    chaInfo.put("MoviesVal", array.get(i).get("houNum"));
                    break;
                }
            }
        }

        chaInfo.remove("Rests");
        chaInfo.remove("HouInfoId");
        chaInfo.remove("IsGas");
        chaInfo.remove("IsWater");
        chaInfo.remove("ChaId");
        return JsonResult.success(chaInfo);
    }

    /**
     * 查询签约流程第五步数据;
     *
     * @param pactId
     * @return
     */
    @Override
    public JsonResult getPactSignFive(String pactId) {
        Map<String, Object> params = signedProviderMapper.getHidAndHConIdByPactId(pactId);
        if (MapUtils.getInteger(params, "IfOperaType").equals(1)) {
            params.remove("HouConId");
        }
        String houId = MapUtils.getString(params, "HouId");
        String houConId = MapUtils.getString(params, "HouConId");
        return JsonResult.success(CustomMap.create("dataList", epcFeign.getHousingConfigList(houId, houConId).getResult())
                .put("SixDataUrl", signedProviderMapper.getPactSignSix(pactId)));
    }

    /**
     * 功能描述:
     * 根据合同编号获取合同第八步资料
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/3/20 14:17
     */
    public Map<String, Object> getPactSignEight(Map<String, Object> params) {
        Map<String, Object> getPactSignEight = signedProviderMapper.getPactSignEight(params);


        double WaterCount = 0;//第一次水
        double GasCount = 0;//第一次燃
        double NetCount = 0;//第一次宽


        double WaterPricings = 0;//水费每月固定金额
        double GasPricings = 0;//燃气费每月固定金额
        double BroadBand = MapUtils.getDouble(getPactSignEight,"BroadBand");//宽带费每月固定
        JsonResult GmioResult = gmioFeign.getChaId(getPactSignEight);
        Map<String,Object> GmioMap = (Map<String, Object>) GmioResult.get("result");
        if (MapUtils.getInteger(getPactSignEight,"IsWater")==1){
            WaterPricings =MapUtils.getDouble(GmioMap,"WaterPricings");
        }
        if (MapUtils.getInteger(getPactSignEight,"IsGas")==1){
            GasPricings =MapUtils.getDouble(GmioMap,"GasPricings");
        }


        //实际租金=实际月租金*付款方式()BillMonthPrice
        double ActualRent = 0;
        if (FieldCheckUtil.isMapFieldNotNull(getPactSignEight, new String[]{"PaActMonthPrice","Firstmonth","BillMonthPrice"})) {
            //实际月租金
            Double PaActMonthPrice = Double.valueOf(getPactSignEight.get("PaActMonthPrice").toString());

            //zc修改（实际租金等于首月+账单金额*（付款方式-1））
            Double Firstmonth = Double.valueOf(getPactSignEight.get("Firstmonth").toString()); //首月金额
            Double BillMonthPrice = Double.valueOf(getPactSignEight.get("BillMonthPrice").toString());//账单金额
            Double actualDeposit = Double.valueOf(getPactSignEight.get("actualDeposit").toString());//房屋押金


            Integer Pmethod = Integer.valueOf(getPactSignEight.get("Pmethod").toString());

            switch (Pmethod) {
                case 0://月付
                    // ActualRent = CompuUtils.mul(PaActMonthPrice, 1);
                    ActualRent = Firstmonth;
                    WaterCount = WaterPricings;
                    GasCount = GasPricings;
                    NetCount = BroadBand;

                    break;
                case 1://季付
                    // ActualRent = CompuUtils.mul(PaActMonthPrice, 3);
                    ActualRent = CompuUtils.add(Firstmonth,CompuUtils.mul(BillMonthPrice,2));
                    WaterCount = CompuUtils.mul(WaterPricings,3);
                    GasCount = CompuUtils.mul(GasPricings,3);
                    NetCount = CompuUtils.mul(BroadBand,3);

                    break;
                case 2://半年付
                    // ActualRent = CompuUtils.mul(PaActMonthPrice, 6);
                    ActualRent = CompuUtils.add(Firstmonth,CompuUtils.mul(BillMonthPrice,5));
                    WaterCount = CompuUtils.mul(WaterPricings,6);
                    GasCount = CompuUtils.mul(GasPricings,6);
                    NetCount = CompuUtils.mul(BroadBand,6);

                    break;
                case 3://年付
                    // ActualRent = CompuUtils.mul(PaActMonthPrice, 12);
                    ActualRent = CompuUtils.add(Firstmonth,CompuUtils.mul(BillMonthPrice,11));
                    WaterCount = CompuUtils.mul(WaterPricings,12);
                    GasCount = CompuUtils.mul(GasPricings,12);
                    NetCount = CompuUtils.mul(BroadBand,12);
                    break;
            }
            log.info("ActualRent----" + ActualRent);
            //租金
            getPactSignEight.put("ActualRent", ActualRent);//第一次支付
            getPactSignEight.put("WaterCount", WaterCount);//第一次支付水
            getPactSignEight.put("GasCount", GasCount);//第一次支付燃
            getPactSignEight.put("NetCount", NetCount);//第一次支付宽
            //房租押金
            double RentDeposit = 0;
            //房屋押金大于零
            if ((int) getPactSignEight.get("Deposit") > 0) {
                //RentDeposit = CompuUtils.mul(PaActMonthPrice, Double.valueOf(getPactSignEight.get("Deposit").toString()));

                RentDeposit = CompuUtils.mul(actualDeposit, Double.valueOf(getPactSignEight.get("Deposit").toString()));
                getPactSignEight.put("RentDeposit", RentDeposit);
            } else {
                getPactSignEight.put("RentDeposit", 0);//房租押金
            }

        } else {
            getPactSignEight.put("ActualRent", 0);//第一次支付
            getPactSignEight.put("RentDeposit", 0);//房租押金
        }
        return getPactSignEight;
    }

    /**
     * 功能描述:
     * 根据租客编号获取租客合同列表
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/3/23 12:01
     */
    public List<Map<String, Object>> getPactList(Map<String, Object> params) {
        List<Map<String, Object>> getPactList = signedProviderMapper.getPactList(params);
        Integer cout = tcmktTenantBlaMapper.getTenantBlaCount(params);
        for (Map<String, Object> getPactMap : getPactList) {
            if (cout > 0) {
                getPactMap.put("TenantBlaCount", 1);
            } else {
                getPactMap.put("TenantBlaCount", 0);
            }
            //图片处理
            if (!StringUtils.isNotBlank(MapUtils.getString(getPactMap, "ShowImg"))) {
                getPactMap.put("ShowImg", ConstantsHousing.DefaultHousingImg);
            }
        }

        return getPactList;
    }

    /**
     * 功能描述:
     * 根据租客编号获取租客合同列表总数
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/3/23 12:01
     */
    public Integer getPactListCount(Map<String, Object> params) {
        Integer getPactListCount = signedProviderMapper.getPactListCount(params);
        return getPactListCount;
    }
}